function getRandomColor() {
  const rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length === 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}
const qiniu = require("../../utils/qnutils");
var { http } = require('../../utils/apiutils');
var format = require('../../utils/util')

Page({
  /**
   * 页面的初始数据
   */
  inputValue: '',
  data: {
    sleft: "0rpx",
    active: 0,
    show: false,
    src: '',
    dataList: [],
    newVideo: {},
    video_real_time: 0, //实时播放进度
    start_time: 0,
    startTime: '',// 视频开始播放，当下的时间
    endTime: '',//视频结束，当下的时间
    initial_time: '', //视频跳转进度 秒
    groupId: "",
    trainingId: "",
    passType: "",
    dt: {
      title: "",
      message: "",
      next: "",
      back: "",
      isd: false,
    },
    isPlay: false,  // 视频是否在播放
    playTimer: null,   // 无人检测  定时器
    isInitiative: false,  // 无人检测定时器结束自动播放视频
    testModal: false,
    minute_5: false,// 5分钟弹一次的弹窗，是否弹过  弹过3后需置为false
    direction: false, // 视频是否全屏播放
    token: '',
    random: {},
    // saveProgress_3:null,
  },
  imgH: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width;
    var swiperH = winWid * imgh / imgw + "px" //等比设置swiper的高度。  即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度    ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
      Hei: swiperH, //设置高度
    })
  },
  //提交数据
  onClickSumbit: function () {
    var data = {
      trainingId: this.data.trainingId,
      videoId: this.data.newVideo.id,
    }
    if (this.data.passType == 1) {
      var submitResultBos = [];
      for (var i = 0; i < this.data.newVideo.questionVoList.length; i++) {
        var cell = this.data.newVideo.questionVoList[i];
        if (cell.answer && cell.answer.length > 0) {
          var p = {
            questionId: cell.id,
            results: cell.answer
          }
          submitResultBos.push(p);
        } else {
          wx.showToast({
            title: '请选择回答所有题目后提交答案',
            icon: "none"
          })
          return
        }
      }
      data["submitResultBos"] = submitResultBos;
    } else {
      data.submitResultBos = []
    }
    wx.showLoading({
      title: '提交数据中...',
    })
    this.doSubmitResult(data)

    // // this.setData({
    // //   show: true,
    // // })
  },
  doSubmitResult: function (data) {
    var that = this;
    http.submitResult(data,
      function (res) {
        wx.hideLoading()
        console.log("----答题结果-----", res, that.data.passType);
        if (res.status == 200) {
          if (that.data.passType == 1) {
            if (res.data.result == 1) {
              console.log("------答题正确---")
              that.setData({
                dt: {
                  title: "答题成功！",
                  message: "恭喜您成功通过本次答题 可继续挑战下一环节",
                  isd: true,
                  back: "返回学习",
                  next: "观看下一个视频",
                },
                show: true,
              })
            } else {
              console.log("------答题错误-----")
              var err = []
              var arr = res.data.submitResult;
              for (var i = 0; i < arr.length; i++) {
                let item = arr[i];
                if (item == 0) {
                  err.push(i + 1);
                }
              }
              that.setData({
                dt: {
                  title: "答题错误！",
                  message: "您所做的题目中，第" + err.join(",") + "错误，请您仔细阅读视频后重新提交",
                  isd: false,
                  back: "返回学习",
                },
                show: true,
              })
            }
          } else {

            if (that.data.dataList.length - 1 == that.data.active) {
              wx.showToast({
                title: '您已学完所有课程',
                icon: "none",
              })
              // that.getTrainData({
              //   groupId: groupId,
              //   trainingId: trainingId}
              // )
              // return
              that.data.dataList[that.data.active].state = 1;
              that.setData({
                active: active,
                newVideo: that.data.dataList[active],
                dataList: that.data.dataList,
              })
              wx.navigateBack({
                url: '/pages/course/course',
              })

            } else {
              that.data.dataList[that.data.active].state = 1;
              var active = parseInt(that.data.active) + 1
              that.setData({
                active: active,
                newVideo: that.data.dataList[active],
                dataList: that.data.dataList,
              })
              wx.showToast({
                title: '正在播放下一个视频',
                icon: "none",
              })
              setTimeout(function () {
                that.videoContext.play();
              }, 2000)
              // console.log("---------------",active,that.data.newVideo);
            }
          }
        } else {
          wx.showToast({
            title: '提交数据失败，请重试',
            icon: "none",
            duration: 2000
          })
          wx.hideLoading()
          wx.navigateBack({
            url: '/pages/course/course',
          })
        }
      },
      function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '提交数据失败，请重试',
          icon: "none",
          duration: 2000
        })
        wx.navigateBack({
          url: '/pages/course/course',
        })

      })
  },
  back: function () {
    this.setData({
      show: false,
    })
  },
  onclickNext: function () {
    this.data.dataList[this.data.active].state = 1;
    var active = parseInt(this.data.active) + 1
    this.setData({
      active: active,
      show: false,
      newVideo: this.data.dataList[active],
      dataList: this.data.dataList,
      video_real_time: 0
    })
    wx.showToast({
      title: '正在播放下一个视频',
      icon: "none",
    })
    var that = this;
    setTimeout(function () {
      that.videoContext.play();
    }, 2000)
  },
  onIpItemClick: function (e) {
    var index = e.currentTarget.dataset.index;
    // this.setScUI(index);
    let item = this.data.dataList[index];
    if (item.state == 1) {

      var crt = this.data.dataList[index].insertTime
      this.setData({
        active: index,
        newVideo: this.data.dataList[index],
      })
      var that = this;
      setTimeout(function () {
        if (crt) {
          console.log("--------跳转进度------", that.data.newVideo.video_real_time);
          that.videoContext.seek(crt);
        }
        that.videoContext.play();
      }, 300)

    }
    else {
      wx.showToast({
        title: '请按照顺序学习',
        icon: "none"
      })
    }

  },
  setScUI: function (index) {
    this.setData({
      sleft: 120 * index,
    })
  },
  // 监听轮播
  onChange(e) {
    this.setData({
      currentNum: e.detail.current,
    })
  },

  timeUpdate: function (e) {
    var aa = 1; // 是否开启可以视频快进 1 禁止开启
    //跳转到指定播放位置 initial-time 时间为秒
    let that = this;
    //播放的总时长
    var duration = e.detail.duration
    //实时播放进度 秒数
    var currentTime = parseInt(e.detail.currentTime)
    //当前视频进度
    // console.log("视频播放到第" + currentTime + "秒")//查看正在播放时间，以秒为单位
    if (that.data.video_real_time == 0) {
      var jump_time = parseInt(that.data.initial_time) + parseInt(that.data.video_real_time)
    } else {
      var jump_time = parseInt(that.data.video_real_time)
    }
    // console.log("------当前进度----", currentTime);
    this.data.dataList[this.data.active].insertTime = currentTime;
    if (aa == 1) {
      if (currentTime > jump_time && currentTime - jump_time > 3) {
        if (this.data.passType == 2 && this.data.newVideo.state == 0) {
          let videoContext = wx.createVideoContext('myVideo')
          videoContext.seek(that.data.video_real_time)
          wx.showToast({
            title: '未完整看完该视频，不能快进',
            icon: 'none',
            duration: 2000,
          })
        }
      }
    }
    // if(e.detail.currentTime<e.detail.duration-15+0.124&&e.detail.duration-15-0.124<e.detail.currentTime){
    //   if(getApp().globalData.popup!=1) return;
    //     this.data.minute_5 = true;
    //     if(this.data.isPlay){
    //       this.data.isInitiative = true;
    //       this.videoContext.pause();
    //     }
    //     this.videoContext.exitFullScreen();
    //     let number = parseInt(Math.random()*(3-0)+0);
    //     let random = JSON.parse(JSON.stringify(getApp().globalData.allQuestion[number]))
    //     wx.nextTick(_=>{
    //       this.setData({
    //         random:random, 
    //         testModal:true
    //       })
    //     })
    // }
    if (currentTime % (5 * 60) == 0 && currentTime != 0) {
      // if(currentTime%5==0&&currentTime!=0){
      if (this.data.minute_5) return;
      if (getApp().globalData.popup != 1) return;
      this.data.minute_5 = true;
      if (this.data.isPlay) {
        this.data.isInitiative = true;
        this.videoContext.pause();
      }
      this.videoContext.exitFullScreen();
      let number = parseInt(Math.random() * (3 - 0) + 0);
      let random = JSON.parse(JSON.stringify(getApp().globalData.allQuestion[number]))
      wx.nextTick(_ => {
        this.setData({
          random: random,
          testModal: true
        })
      })

    }
    // 当前方法微信规定250ms执行一次  故需加240ms避免重复触发
    // console.log(e.detail.currentTime)
    let yiban = parseInt(duration / 2);
    // let yiban =12;
    // console.log(getApp().globalData.faceIdentification)
    if (getApp().globalData.faceIdentification == 1 && getApp().globalData.faceType == 1) {
      if (this.data.active == 0) {
        if (yiban < e.detail.currentTime && e.detail.currentTime < yiban + 0.3) {
          if (wx.getStorageSync('hasPai')) return false;
          this.videoContext.pause()
          wx.setStorageSync('hasPai', 1)
          this.data.playTimer = null;
          wx.navigateTo({
            url: '../photograph/photograph',
          })
        }
      }

    } else if (getApp().globalData.faceIdentification == 1 && getApp().globalData.faceType == 2) {
      if (yiban < e.detail.currentTime && e.detail.currentTime < yiban + 0.3) {
        if (wx.getStorageSync('hasPai')) return false;
        this.videoContext.pause()
        wx.setStorageSync('hasPai', 1)
        this.data.playTimer = null;
        wx.navigateTo({
          url: '../photograph/photograph',
        })
      }
    }

    that.setData({
      video_real_time: currentTime, //实时播放进度
    })
  },
  videoBindplay(e) {
    this.setData({
      startTime: format.formatTimeTwo(new Date())
    })
    this.data.isPlay = true;
    // this.videoStartEnd()
    this.saveProgress(this.data.video_real_time)
    // this.save30()
    console.log('触发播放')
  },
  videoBindended() {
    console.log('视频结束')
    // this.videoStartEnd(this.data.video_real_time)
    this.saveProgress(this.data.video_real_time)
    this.data.start_time = 0;
    if (this.data.passType == 2) {
      if (this.data.newVideo.state == 0) {
        this.onClickSumbit();
      }
      else {
        this.onclickNext();
      }
    }
    this.setData({
      video_real_time: 0,
    })
  },

  videoBindpause: function (e) {
    this.setData({
      endTime: format.formatTimeTwo(new Date())
    })
    this.data.isPlay = false;
    this.videoStartEnd(this.data.video_real_time)
    this.saveProgress(this.data.video_real_time)
    setTimeout(_ => {
      this.data.start_time = this.data.video_real_time;
    }, 2000)
    console.log('视频暂停')
  },
  videoErrorCallback(e) {
    console.log(e, '视频错误信息:')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    //此处写在接口的位置 100从接口处获取
    that.setData({
      initial_time: '100' //视频进度
    })
    var {
      groupId,
      trainingId,
      passType,
      name
    } = options;
    wx.setNavigationBarTitle({
      title: name,
    })
    this.setData({
      groupId: groupId,
      trainingId: trainingId,
      passType: passType
    })
    this.getTrainData({
      groupId: groupId,
      trainingId: trainingId
    });
    wx.setStorageSync('hasPai', '');
  },
  onclickCell: function (e) {
    var cellid = e.currentTarget.dataset.cellid; //答案对象
    var item = e.currentTarget.dataset.item; //问题对象
    var index = e.currentTarget.dataset.index;
    // var arr = this.data.dataList[index]
    var arr = item.answer;
    if (arr) {

      if (item.isMultiple == 0) {
        if (arr.indexOf(cellid) != -1) {
          arr.remove(cellid);
        } else {
          arr[0] = cellid;
        }
      } else {
        if (arr.indexOf(cellid) != -1) {

          arr.remove(cellid);
          console.log("----2222----", arr, cellid);
        } else {
          console.log("----333----", arr, cellid);
          arr.push(cellid);
        }

      }

    } else {
      arr = [];
      arr.push(cellid);
    }
    console.log("-----66666----", arr)
    this.data.newVideo.questionVoList[index].answer = arr;
    this.setData({
      newVideo: this.data.newVideo,
    })
    console.log("----最终结果---------", this.data.newVideo);

  },

  getTrainData: function (data) {
    // var p = {
    //   groupId: data.groupId, //视频组id
    //   trainingId:data.trainingId, //培训id
    // }
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getTrainData(data,
      function (res) {
        wx.hideLoading()
        console.log("---------", res);
        if (res.status == 200) {
          let arr = res.data;
          if (arr.length > 0) {
            for (var i in arr) {
              let element = arr[i]
              if (element.state == 0) {
                that.setData({
                  active: i
                })
                break;
              }
            };
            that.setData({
              video_real_time: arr[that.data.active].progress,
              dataList: arr,
              newVideo: arr[that.data.active],
            })
            console.log('视频列表', that.data.dataList)
            // that.videoContext.seek(arr[that.data.active].progress)
            that.data.start_time = arr[that.data.active].progress
          } else {
            that.setData({
              dataList: [],
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('hasPai')) {
      let url = wx.getStorageSync('hasPai');
      this.getUpToken(url);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('进入后台')
    clearTimeout(this.data.playTimer);
    // this.data.saveProgress_3=null;
    // clearTimeout(this.data.saveProgress_3);
    // this.videoStartEnd(this.data.video_real_time)
    // this.saveProgress(this.data.video_real_time)

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('页面卸载')
    clearTimeout(this.data.playTimer);
    // clearTimeout(this.data.saveProgress_3);
    // this.data.playTimer = null;
    // this.data.saveProgress_3=null;
    wx.setStorageSync('hasPai', '');
    // this.videoStartEnd(this.data.video_real_time)
    // this.saveProgress(this.data.video_real_time)

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  minute5() {
    let _this = this;
    if (this.data.isPlay) {
      // 视频正在播放的话，做标记    
      this.data.isInitiative = true;
      this.videoContext.pause();
    }
    this.setData({
      testModal: true
    })
    clearTimeout(_this.data.playTimer);
    _this.data.playTimer = null;
    let timer5 = setTimeout(() => {
      this.data.minute_5 = false;
      clearTimeout(timer5);
    }, 3000)
  },
  hidetest() {
    if (this.data.isInitiative) {
      // 判断开始前视频是否是正在播放的状态
      this.videoContext.play();
      this.data.isInitiative = false;
    }
    this.setData({
      testModal: false
    })
    let timer5 = setTimeout(() => {
      this.data.minute_5 = false;
      clearTimeout(timer5);
    }, 3000)
  },
  saveProgress() {
    let params = {
      trainingId: this.data.trainingId,
      videoId: this.data.dataList[this.data.active].id,
      progress: this.data.video_real_time
    }
    http.uploadingVideoProgress(params, (res) => {
      if (res.status == 200) {
        // console.log('传递的参数', params, res)
      } else {
        wx.showToast({
          title: res.message,
        })
      }
    }, (err) => {
      wx.hideLoading({
        success: (res) => { },
      })
    })
  },
  videoFullScreen(e) {
    this.setData({
      direction: e.detail.fullscreen
    })
  },
  getUpToken(url) {
    console.log('getUpToken', url)
    var that = this;
    http.getUpToken({},
      function (res) {
        // console.log("----七牛云的授权码---", res);
        qiniu.initQiniu(res.data);
        wx.nextTick(_ => {
          that.upDataImage(url);
        })
      },
      function (err) {

      })
  },
  uploadFace() {
    console.log('show进入');
    if (!wx.getStorageSync('hasPai')) return;
    let params = {
      trainingId: this.data.trainingId,
      url: wx.getStorageSync('hasPai'),
      groupId: this.data.groupId
    }
    http.faceAuth(params, (res) => {
      if (res.status == 200) {
        that.videoContext.play();
      } else {
        this.uploadFace()
        // wx.showToast({
        //   title: res.message,
        //   icon:"none"
        // })
      }
    }, (err) => {
      wx.hideLoading({
        success: (res) => { },
      })
    })
  },
  upDataImage: function (tempFilePaths) {
    console.log('upDataImage', tempFilePaths)
    var that = this;
    qiniu.getUploadImgae(tempFilePaths,
      function (res) {
        console.log('res', res)
        var data = {
          url: res.key,
          trainingId: that.data.trainingId,
          groupId: that.data.groupId,
        }
        that.faceAuth(data)
      },
      function (err) {
        console.log(err)
      })
  },
  sumbituploadingVideoProgress: function (times) {
    var that = this;
    var data = {
      "progress": times, //观看进度   单位秒  观看结束传 -1
      "videoId": this.data.newVideo.id //视频id
    }
    http.sumbituploadingVideoProgress(data,
      function (res) { },
      function (err) {
        wx.hideLoading()
      })
  },
  faceAuth: function (data) {
    var that = this;
    console.log("-----头像链接---------", data);
    http.faceAuth(data,
      function (res) {
        if (res.status == 200) {
          wx.showToast({
            title: '认证成功',
            icon: "none",
          })
          setTimeout(_ => {
            that.videoContext.play();
          }, 500)
          let timer = setTimeout(() => {
            wx.setStorageSync('hasPai', '');
            clearTimeout(timer);
            timer = undefined;
          }, 30000)
        } else {
          wx.showToast({
            title: '认证失败,重新认证',
            success() {
              setTimeout(_ => {
                wx.navigateTo({
                  url: '../photograph/photograph',
                })
              }, 1000)
            }
          })
        }
      },
      function (err) {

      })

  },

  videoStartEnd(time) {
    let params = {
      "trainingId": this.data.trainingId,	//培训id
      "videoId": this.data.newVideo.id,	//视频id
      "type": time ? 1 : 0,		//记录类型 0.开始播放	1.结束播放
      "duration": time * 1 - this.data.start_time * 1,
      "startTime": this.data.startTime, //当下时间
      "endTime": this.data.endTime //当下时间
    }
    if (!params.startTime) { return }
    http.videoSave(params, res => {
      this.setData({
        startTime: '',
        endTime: ''
      })
    }, err => { })
  },
  // save30(){
  //   // 30s 保存一次视频进度
  //   console.log('调用调用')
  //   if(this.data.saveProgress_3) {
  //     clearTimeout(this.data.saveProgress_3)
  //   }
  //   let saveProgress_3 = setTimeout(_=>{
  //     this.saveProgress()
  //     this.save30()
  //   },30000)
  //   this.setData({
  //     saveProgress_3:saveProgress_3
  //   })
  // }
})

Array.prototype.remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};